package hot_100;

/**
 * @author: Darven
 * @createTime: 2025-10-01  00:24
 * @description: TODO
 */
public class P2 {
    public static void main(String[] args) {
        ListNode a1 = new ListNode(2);
        a1.next = new ListNode(4);
        a1.next.next = new ListNode(3);

        ListNode a2 = new ListNode(5);
        a2.next = new ListNode(6);
        a2.next.next = new ListNode(4);
        P2 p2 = new P2();
        ListNode node = p2.addTwoNumbers(a1, a2);

        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(-1);
        ListNode node = ans;
        int j = 0;
        while (l1 != null || l2 != null) {
            int val1 = l1 != null ? l1.val : 0;
            int val2 = l2 != null ? l2.val : 0;

            int i=val1+val2+j;
            j=i/10;
            i%=10;
            node.next=new ListNode(i);
            node=node.next;

            if(l1!=null) l1=l1.next;
            if(l2!=null) l2=l2.next;
        }

        if(j>0){
            node.next=new ListNode(j);
        }

        return ans.next;
    }
}
